<template>
  <div class="api-example">
    <h2>HTTP请求封装使用示例</h2>
    
    <!-- 用户登录示例 -->
    <el-card class="example-card">
      <template #header>
        <h3>用户登录示例</h3>
      </template>
      
      <el-form :model="loginForm" @submit.prevent="handleLogin">
        <el-form-item label="姓名">
          <el-input v-model="loginForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="学校">
          <el-input v-model="loginForm.school" placeholder="请输入学校" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="loginForm.class" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="loginForm.studentId" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="userLoading" 
            @click="handleLogin"
          >
            {{ userLoading ? '登录中...' : '登录' }}
          </el-button>
          <el-button 
            v-if="isLoggedIn" 
            @click="handleLogout"
          >
            退出登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div v-if="userInfo" class="user-info">
        <h4>当前用户信息：</h4>
        <p>姓名：{{ userInfo.name }}</p>
        <p>学校：{{ userInfo.school }}</p>
        <p>班级：{{ userInfo.class }}</p>
        <p>学号：{{ userInfo.studentId }}</p>
      </div>
    </el-card>

    <!-- 测试相关示例 -->
    <el-card class="example-card">
      <template #header>
        <h3>测试功能示例</h3>
      </template>
      
      <div class="quiz-actions">
        <el-button 
          type="primary" 
          :loading="quizLoading" 
          @click="loadQuestions"
        >
          {{ quizLoading ? '加载中...' : '加载测试题目' }}
        </el-button>
        
        <el-button 
          type="success" 
          :loading="quizLoading" 
          @click="submitTestAnswers"
        >
          {{ quizLoading ? '提交中...' : '提交测试答案' }}
        </el-button>
        
        <el-button 
          type="info" 
          :loading="quizLoading" 
          @click="loadUserResults"
        >
          {{ quizLoading ? '加载中...' : '查看历史结果' }}
        </el-button>
      </div>
      
      <div v-if="questions.length > 0" class="questions-info">
        <h4>题目信息：</h4>
        <p>共 {{ questions.length }} 道题目</p>
      </div>
      
      <div v-if="currentResult" class="result-info">
        <h4>最新测试结果：</h4>
        <p>分数：{{ currentResult.score }}</p>
        <p>分析：{{ currentResult.analysis }}</p>
      </div>
      
      <div v-if="userResults.length > 0" class="history-results">
        <h4>历史测试结果：</h4>
        <ul>
          <li v-for="result in userResults" :key="result.id">
            {{ result.category }} - 分数：{{ result.score }} - 时间：{{ result.completedAt }}
          </li>
        </ul>
      </div>
    </el-card>

    <!-- 文件上传示例 -->
    <el-card class="example-card">
      <template #header>
        <h3>文件上传示例</h3>
      </template>
      
      <div class="upload-section">
        <el-upload
          :before-upload="handleFileUpload"
          :show-file-list="false"
          accept="image/*"
        >
          <el-button type="primary" :loading="isUploading">
            {{ isUploading ? '上传中...' : '选择图片上传' }}
          </el-button>
        </el-upload>
        
        <el-progress 
          v-if="uploadProgress > 0" 
          :percentage="uploadProgress" 
          class="upload-progress"
        />
      </div>
      
      <div class="avatar-upload">
        <el-upload
          :before-upload="handleAvatarUpload"
          :show-file-list="false"
          accept="image/*"
        >
          <el-button type="success" :loading="isUploading">
            {{ isUploading ? '上传中...' : '上传头像' }}
          </el-button>
        </el-upload>
      </div>
    </el-card>

    <!-- 统计数据示例 -->
    <el-card class="example-card">
      <template #header>
        <h3>统计数据示例</h3>
      </template>
      
      <div class="stats-actions">
        <el-button 
          type="primary" 
          :loading="statsLoading" 
          @click="loadUserStats"
        >
          {{ statsLoading ? '加载中...' : '获取用户统计' }}
        </el-button>
        
        <el-button 
          type="info" 
          :loading="statsLoading" 
          @click="loadSystemStats"
        >
          {{ statsLoading ? '加载中...' : '获取系统统计' }}
        </el-button>
      </div>
      
      <div v-if="userStats" class="user-stats">
        <h4>用户统计：</h4>
        <pre>{{ JSON.stringify(userStats, null, 2) }}</pre>
      </div>
      
      <div v-if="systemStats" class="system-stats">
        <h4>系统统计：</h4>
        <pre>{{ JSON.stringify(systemStats, null, 2) }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 导入封装好的composables
import { useUser, useQuiz, useFileUpload, useStats } from '../composables/useApi'

// 使用封装好的composables
const { 
  userInfo, 
  isLoading: userLoading, 
  isLoggedIn, 
  login, 
  logout, 
  initUser 
} = useUser()

const { 
  questions, 
  currentResult, 
  userResults, 
  isLoading: quizLoading, 
  fetchQuestions, 
  submitAnswers, 
  fetchUserResults 
} = useQuiz()

const { 
  isUploading, 
  uploadProgress, 
  uploadFile, 
  uploadAvatar 
} = useFileUpload()

const { 
  userStats, 
  systemStats, 
  isLoading: statsLoading, 
  fetchUserStats, 
  fetchSystemStats 
} = useStats()

// 登录表单数据
const loginForm = reactive({
  name: '',
  school: '',
  class: '',
  studentId: ''
})

// 初始化用户状态
onMounted(() => {
  initUser()
})

// 处理登录
const handleLogin = async () => {
  try {
    await login(loginForm)
    ElMessage.success('登录成功！')
  } catch (error) {
    ElMessage.error('登录失败，请重试')
  }
}

// 处理登出
const handleLogout = async () => {
  await logout()
}

// 加载测试题目
const loadQuestions = async () => {
  try {
    await fetchQuestions('personality')
    ElMessage.success('题目加载成功！')
  } catch (error) {
    ElMessage.error('题目加载失败')
  }
}

// 提交测试答案（示例）
const submitTestAnswers = async () => {
  try {
    // 模拟答案数据
    const mockAnswers = [
      { questionId: 1, answer: 'A' },
      { questionId: 2, answer: 'B' },
      { questionId: 3, answer: 'C' }
    ]
    
    await submitAnswers('personality', mockAnswers)
    ElMessage.success('答案提交成功！')
  } catch (error) {
    ElMessage.error('答案提交失败')
  }
}

// 加载用户测试结果
const loadUserResults = async () => {
  try {
    await fetchUserResults()
    ElMessage.success('历史结果加载成功！')
  } catch (error) {
    ElMessage.error('历史结果加载失败')
  }
}

// 处理文件上传
const handleFileUpload = async (file: File) => {
  try {
    const result = await uploadFile(file, 'image')
    console.log('文件上传结果：', result)
    return false // 阻止默认上传行为
  } catch (error) {
    return false
  }
}

// 处理头像上传
const handleAvatarUpload = async (file: File) => {
  try {
    const result = await uploadAvatar(file)
    console.log('头像上传结果：', result)
    return false // 阻止默认上传行为
  } catch (error) {
    return false
  }
}

// 加载用户统计
const loadUserStats = async () => {
  try {
    await fetchUserStats()
    ElMessage.success('用户统计加载成功！')
  } catch (error) {
    ElMessage.error('用户统计加载失败')
  }
}

// 加载系统统计
const loadSystemStats = async () => {
  try {
    await fetchSystemStats()
    ElMessage.success('系统统计加载成功！')
  } catch (error) {
    ElMessage.error('系统统计加载失败')
  }
}
</script>

<style scoped>
.api-example {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.example-card {
  margin-bottom: 20px;
}

.user-info,
.questions-info,
.result-info,
.history-results,
.user-stats,
.system-stats {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.quiz-actions,
.stats-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.upload-section,
.avatar-upload {
  margin-bottom: 15px;
}

.upload-progress {
  margin-top: 10px;
}

.history-results ul {
  list-style-type: none;
  padding: 0;
}

.history-results li {
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

pre {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
}
</style>